//
//  CTVRootChannelMenuController.m
//  Channltv
//
//  Created by Bruno Keymolen on 07/09/07.
//  Copyright 2007 channl.tv. All rights reserved.
//

#import "CTVRootChannelMenuController.h"
#import "CTVIconPreviewController.h"
#import "CTVChannelMenuController.h"
#import "CTVCache.h"

@implementation CTVRootChannelMenuController


- (id) initWithScene: (BRRenderScene *) scene andRootChannel:(CTVRootChannel*)rootChannel{
	NSLog(@"CTVRootChannelMenuController - initWithScene");

    if( [super initWithScene: scene] == nil ){
        return ( nil );
	}


	[rootChannel retain];
	m_rootChannel = rootChannel;	

		
	[self setListTitle: [rootChannel name]];	
	[self setPreSelectedIndex];

	//Fixed string "channels"; should later be replaced by [rootChannel thumbUrl] or so 
	NSString* iconPath =  [[NSBundle bundleForClass: [self class]] pathForResource:@"channels" ofType: @"png"];
	BRTexture * tex = [CTVCache createBitmapTextureFromPath:iconPath withScene:[self scene]];	
	[self setListIcon:tex];
			
	 // initialize your resources here
	[[self list] setDatasource: self];
	
				
	return self;
}



- (void) dealloc
{
	NSLog(@"CTVRootChannelMenuController - dealloc");

	[m_rootChannel release];
	
		
	[super dealloc];
}



- (long) itemCount
{
    // return the number of items in your menu list here
	return ( [ [m_rootChannel channels] count] );
}


- (id<BRMenuItemLayer>) itemForRow: (long) row
{
    // build a BRTextMenuItemLayer or a BRAdornedMenuItemLayer, etc. here
    // return that object, it will be used to display the list item.
	if ( row >= [[m_rootChannel channels] count] )
		return ( nil );

	id result;

	CTVChannel* channel = [[[m_rootChannel channels] allValues] objectAtIndex:row];	

	if([[channel clips] count] > 0){	
		result = [BRAdornedMenuItemLayer adornedFolderMenuItemWithScene: [self scene]];
	}else{
		result = [BRAdornedMenuItemLayer adornedMenuItemWithScene: [self scene]];		
	}
	[[result textItem] setTitle: [channel name]];
				
	return ( result );
}


- (NSString *) titleForRow: (long) row
{
    if ( row >= [[m_rootChannel channels] count] )
		return ( nil );

	CTVChannel* channel = [[[m_rootChannel channels] allValues] objectAtIndex:row];	

	return ( [channel name] );
}


- (long) rowForTitle: (NSString *) title
{
    long result = -1;
    long i, count = [self itemCount];
    for ( i = 0; i < count; i++ )
    {
        if ( [title isEqualToString: [self titleForRow: i]] )
        {
            result = i;
            break;
        }
    }
    
    return ( result );
}

- (void) itemSelected: (long) row
{
	NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

	// This is called when the user presses play/pause on a list item
	CTVChannel* channel = [[[m_rootChannel channels] allValues] objectAtIndex:row];	//A channel contains a collection of clips
	
	if([[channel clips] count] > 0){
	
		CTVChannelMenuController* controller = [[[CTVChannelMenuController alloc] initWithScene:[self scene] andChannel:channel] autorelease];	
		[[self stack] pushController: controller];
	}

	[pool release];
}


- (id<BRMediaPreviewController>) previewControllerForItem: (long) item
{
	if ( item >= [[m_rootChannel channels] count] )
		return ( nil );


    // If subclassing BRMediaMenuController, this function is called when the selection cursor
    // passes over an item.
	CTVChannel* channel = [[[m_rootChannel channels] allValues] objectAtIndex:item];	
		
	CTVIconPreviewController* iconPreview = nil;
	CGImageRef image = nil;
	
	image = [[CTVCache GetInstance] CreateImageForURLString:[channel thumbUrl]];
	if(image != nil){
		NSLog( @"Image from cache : %@" , [channel thumbUrl]);
		iconPreview = [[CTVIconPreviewController alloc] initWithScene:[self scene] andImage:image andYRotation:40.0f];
	}
	
	//Fallback; get it from its location 
	if(image == nil){
		NSURL* url = nil;
		if( [[channel thumbUrl] hasPrefix:@"http"] == YES){
			url = [NSURL URLWithString:[channel thumbUrl]];
		}else{
			url = [NSURL fileURLWithPath:[channel thumbUrl]];	
		}
		if(image != nil){
			NSLog( @"Image from location : %@" , [channel thumbUrl]);
			image = (CGImageRef)CreateImageForURL( url );	
			iconPreview = [[CTVIconPreviewController alloc] initWithScene:[self scene] andImage:image andYRotation:40.0f];
		}
	}
	
	[iconPreview autorelease];
		
	return ( iconPreview );
}





/*
 * CTVSyncListener
 */
-(void)syncStarted{
}

-(void)syncStopped{
	//Some control for our selection selector 
	long row = [(BRListControl*)[self list] selection];
	long max = 0.0 + [[m_rootChannel channels] count];
	if ( row >= max ){
		[(BRListControl*)[self list] setSelection:max-1];		
	}

	//Redraw menu
	[self resetLayout];
	[self refreshControllerForModelUpdate];
				
	//Still did not found a cleaner way to force a redraw of the menuitems
	NSArray* co = [self controls];
	int a;
	for(a=0;a<[co count];a++){
		BRControl* bc = [co objectAtIndex:a];
		[[bc layer] reload]; 
	}	
	[[self scene] renderScene]; 		

		
}

//Called after the sync process but before existing clips/channels are deleted from mem
-(void)syncWillFinish{ 
}


- (id)popAnimation{
	id animation = [super popAnimation];
	return animation;
}

- (id)pushAnimation{
	id animation = [super pushAnimation];
	return animation;
}


//Controller will be displayed on screen 
- (void)willBePushed{
	//Subscribe for sync events (menu updates)
	[[CTVSync GetInstance] addListener:(CTVSyncListener*)self];

	[super willBePushed];
}


//Controller will be taken from screen
- (void)willBePopped{
	//Unsubscribe for sync events
	[[CTVSync GetInstance] removeListener:(CTVSyncListener*)self];

	[super willBePopped];
}


@end
